package com.kmx.demo.metadata;

import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kmx.demo.config.Configuration;
import com.kmx.demo.utils.Request;

public class RegMetadata {

	public static boolean regFgs(String url) {
		ArrayList<String> allFgId = new ArrayList<String>();
		HashMap<String, Integer> status = new HashMap<String, Integer>();

		if (new File("demoData/metadata/fieldGroups").exists()) {
			Path path = Paths.get("demoData/metadata/fieldGroups");
			Charset _charset = Charset.forName("utf-8");

			try (BufferedReader reader = Files.newBufferedReader(path, _charset)) {
				String line = null;
				while ((line = reader.readLine()) != null) {
					JSONObject fg = JSON.parseObject(line);
					String fgId = fg.getString("id");
					int rc = Request.post(url).body(line).headers("Content-Type", "application/json").run()
							.statusCode();
					if (rc == 201) {
						allFgId.add(fgId);
					} else {
						System.out.println("Register field group fail ,return code is " + rc);
						return false;
					}
				}
				reader.close();
				System.out.println("All field group registered,waiting for published");
				Thread.sleep(1000);
				int checker = 0;
				while (status.size() != allFgId.size() && checker <= 5) {
					for (String fgId : allFgId) {
						String res = Request.get(url + "/" + fgId).run().responsePayload();
						JSONObject payload = JSON.parseObject(res);
						if ("PUBLISHED".equalsIgnoreCase(payload.getJSONObject("fieldGroup").getString("status"))
								&& !status.containsKey(fgId)) {
							status.put(fgId, 1);
						}
					}
					if (status.size() == allFgId.size()) {
						return true;
					}
					checker++;

					Thread.sleep(5000);
				}
				if (status.size() != allFgId.size()) {
					return false;
				}

			} catch (Exception x) {
				x.printStackTrace();
				return false;
			}
		} else {
			System.out.println("Can not find the file : demoData/metadata/fieldGroups");
			return false;

		}
		return false;
	}

	public static boolean regAssets(String url) {
		ArrayList<String> allFgId = new ArrayList<String>();
		HashMap<String, Integer> status = new HashMap<String, Integer>();

		if (new File("demoData/metadata/assets").exists()) {
			Path path = Paths.get("demoData/metadata/assets");
			Charset _charset = Charset.forName("utf-8");

			try (BufferedReader reader = Files.newBufferedReader(path, _charset)) {
				String line = null;
				while ((line = reader.readLine()) != null) {
					JSONObject fg = JSON.parseObject(line);
					String fgId = fg.getString("id");
					int rc = Request.post(url).body(line).headers("Content-Type", "application/json").run()
							.statusCode();
					if (rc == 201) {
						allFgId.add(fgId);
					} else {
						System.out.println("Register asset fail ,return code is " + rc);
						return false;
					}
				}
				reader.close();
				System.out.println("All assets registered");

			} catch (Exception x) {
				x.printStackTrace();
				return false;
			}
		} else {
			System.out.println("Can not find the file : demoData/metadata/assets");
			return false;

		}
		return false;
	}

	public static void regMetadata(String sdmServerIp) {

		String regFgUrl = "http://" + sdmServerIp + ":8081/data-service/v2/field-groups";
		String regAssetUrl = "http://" + sdmServerIp + ":8081/data-service/v2/assets";
		if (regFgs(regFgUrl)) {
			regAssets(regAssetUrl);
		}

	}

	public static void main(String[] args) {

		if (args.length == 1) {

			regMetadata(args[0]);
		} else {
			Configuration config = new Configuration();
			regMetadata(config.getSdmIp());
		}

	}

}
